<?php

namespace app\health\service;

use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use think\Exception;
use think\Log;

/**
 * 推广系统业务办理接口
 * @author 张旭鹏 <zxp_lethe@163.com>
 * @date: 2024/4/24
 */
class BusinessService
{
	protected const URL_BASE = 'https://cladmin.xinquanyu.top';

	protected const PID = 40;

	/**
	 * 发送短信办理验证码
	 * @param array $params
	 * @return array|mixed|string
	 * @throws GuzzleException
	 * @throws \JsonException
	 */
	public static function sendCode(array $params = [])
	{
		$form_params = [
			'mobile'      => $params['mobile'],
			'zfCode'      => $params['zf_code'],
			'serviceCode' => strtoupper($params['city_code']),
			'pid'         => self::PID,
			'ip'          => $params['ip'] ?? '',
		];
		try {
			$httpClient = new Client([
				'base_uri' => self::URL_BASE,
				'timeout'  => 30,
			]);
			$response   = $httpClient->request('POST', '/api_v2/index/sendCode', [
				'form_params' => $form_params
			]);
			$content    = json_decode($response->getBody()->getContents(), true, 512, JSON_THROW_ON_ERROR);
			if ($content['code'] === -1) {
				return $content['msg'];
			}
			return ['order_no' => $content['data']['order_no']];
		} catch (Exception $exception) {
			$msg = '业务办理发送验证码接口:' . $exception->getMessage() . PHP_EOL;
			$msg .= '请求参数:' . var_export($form_params, true) . PHP_EOL;
			Log::error($msg);
			return '短信发送失败';
		}
	}

	/**
	 * 业务办理
	 * @param array $params
	 * @return mixed|string|true
	 * @throws GuzzleException
	 * @throws \JsonException
	 */
	public static function handle(array $params = [])
	{
		$form_params = [
			'mobile'      => $params['mobile'],
			'zfCode'      => $params['zf_code'],
			'serviceCode' => strtoupper($params['city_code']),
			'pid'         => self::PID,
			'ip'          => $params['ip'] ?? '',
			'code'        => $params['code'] ?? '',
			'url'         => $params['url'] ?? '',
			'order_no'    => $params['order_no'] ?? '',
			'platform'    => $params['platform'] ?? '',
			'pack'        => $params['pack'] ?? '',
			'click'       => $params['click'] ?? '',
		];
		try {
			$httpClient = new Client([
				'base_uri' => self::URL_BASE,
				'timeout'  => 30,
			]);
			$response   = $httpClient->request('POST', '/api_v2/index/busHandle', [
				'form_params' => $form_params
			]);
			$content    = json_decode($response->getBody()->getContents(), true, 512, JSON_THROW_ON_ERROR);
			if ($content['code'] === -1) {
				return $content['msg'];
			}
			return true;
		} catch (Exception $exception) {
			$msg = '业务办理接口:' . $exception->getMessage() . PHP_EOL;
			$msg .= '请求参数:' . var_export($form_params, true) . PHP_EOL;
			Log::error($msg);
			return '办理失败~';
		}
	}
}